#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>

const char *filename = "log.txt";
const char *textbuff = "hello,file!!!\n";
char readbuff[1024];

int main(){
  //O_CREAT:不存在则新建
  //O_WRONLY:只写方式打开
  //O_RDONLY:只读方式打开
  //O_APPEND:追加方式打开
  //O_TRUNC:打开时执行清空操作
  

  int fd = open(filename,O_WRONLY|O_CREAT|O_APPEND,0666);
  //int fd = open(filename,O_RDONLY|O_CREAT|O_APPEND,0666);//返回值fd是文件描述符数组的下标,该数组是一个指针数组,指向strut_file对象
  
  if(fd<0){
    perror("open error:");
    return 1; 
  }
  
  dup2(1,fd);//重定向,本质是修改文件描述符数组的指针指向

  ssize_t ret = write(fd,textbuff,strlen(textbuff));
  //ssize_t ret = read(fd,readbuff,1024-1);
  //printf("%s",readbuff);
  //printf("%d\n",(int)ret);
  close(fd);

  return 0;
}

